//
//  ChatOrderViewModel.swift
//  Exchange
//
//  Created by rui on 2018/6/13.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

class ChatOrderViewModel: BaseViewModel {

    ///广告会话id
    var adChatId: Int = 0
    ///订单id
    var orderId: Int = 0
    
    ///evaluation 0 好评 1 中评 2 差评
    var evaluation: Int8 = 0
    
    var payPassword: String = ""
    
    
    ///记录通知成功后的时间
    var notifyTime: TimeInterval = 0
    
    ///广告会话对象
    var waitDetailModel: WaitOrderDetailModel?
    
    var orderModel: TradeOrderListModel?
    
    ///根据id获取广告信息
    private lazy var advertisingApi: AdChatInfoRequest = {
        let api = AdChatInfoRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    ///根据订单id获取订单信息
    private lazy var orderInfoApi: TradeOrderInfoRequest = {
        let api = TradeOrderInfoRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    
    private lazy var cancelOrderApi: CancelOredrRequest = {
        let api = CancelOredrRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    private lazy var evaluateOrderApi: EvaluateOrderRequest = {
        let api = EvaluateOrderRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    private lazy var releseCoinApi: ReleseCoinRequest = {
        let api = ReleseCoinRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    private lazy var notifyReleseApi: NotifyReleseCoinRequest = {
        let api = NotifyReleseCoinRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    private lazy var confirmPayApi: ConfirmPayRequest = {
        let api = ConfirmPayRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    ///更新待下单时间
    private lazy var waitOrderUpdateApi: AdChatUpdateRequest = {
        let api = AdChatUpdateRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    ///更新订单时间
    private lazy var orderUpdateApi: OrderChatUpdateRequest = {
        let api = OrderChatUpdateRequest()
        api.dataReformer = self
        api.paramSource = self
        api.delegate = self
        return api
    }()
    
    
    ///更新广告会话时间
    func updateAdChatTime(id: Int) {
        self.adChatId = id
        self.waitOrderUpdateApi.loadData()
    }
    
    ///更新订单会话时间
    func updateOrderChatTime(id: Int) {
        self.orderId = id
        self.orderUpdateApi.loadData()
    }
    
    func loadAdInfo(adChatId: Int) {
        self.adChatId = adChatId
        self.advertisingApi.loadData()
    }
    
    func loadOrderInfo(orderId: Int) {
        self.orderId = orderId
        self.orderInfoApi.loadData()
    }
    
    func cancelOrder(orderId: Int) {
        self.orderId = orderId
        self.cancelOrderApi.loadData()
    }
    ///evaluation 0 好评 1 中评 2 差评
    func evaluateOrder(orderId: Int,evaluation: Int8) {
        self.orderId = orderId
        self.evaluation = evaluation
        self.evaluateOrderApi.loadData()
    }
    
    ///放币
    func releseCoin(orderId: Int,payPassword: String)  {
        self.orderId = orderId
        self.payPassword = payPassword
        self.releseCoinApi.loadData()
    }
    
    ///通知释放币 地址还未修改
    func notifyReleseCoin(orderId: Int) {
        if notifyTime > 0 {
            let curTime = Date().timeIntervalSince1970
            if curTime - notifyTime < 5 * 60 {
                let t = self.getPayTime()
                let text = String(format: kText("请勿频繁点击!%d分钟之后,可发起申诉!"), 30-t)
                CYMBShow.showMessage(text)
                return
            }
        }
        self.orderId = orderId
        self.notifyReleseApi.loadData()
    }
    
    ///付款确认
    func confirmPay(orderId: Int) {
        self.orderId = orderId
        self.confirmPayApi.loadData()
    }
    
    func getTitle()-> String {
        var mon = ""
        var typeString = kText("购买订单")
        if let model = self.orderModel {
            if model.buyer == AppInfo.default.userId {
                typeString = kText("购买订单")
            }else {
                typeString = kText("出售订单")
            }
            mon = model.moneyType ?? ""
        }else if let model = self.waitDetailModel {
            if model.userId == AppInfo.default.userId {
                if model.type == 0 {
                    typeString = kText("购买订单")
                }else {
                    typeString = kText("出售订单")
                }
            }else {
                if model.type == 0 {
                    typeString = kText("出售订单")
                }else {
                    typeString = kText("购买订单")
                }
            }
            mon = model.moneyType ?? ""
        }
        if AppCacheInfo.default.isEnlish {
            mon = mon + " "
        }
        return mon + typeString
    }
    
    ///获取当前确认付款过了多久
    func getPayTime() -> Int {
        var t = 0
        if let timeStr = orderModel?.payConfirmTime {
            let df = DateFormatter()
            df.dateFormat = "yyyy-MM-dd HH:mm:ss"
            df.timeZone = TimeZone(identifier: "Asia/Shanghai")
            let date = df.date(from: timeStr)
            let pay = date?.timeIntervalSince1970
            let now = Date().timeIntervalSince1970
            t = Int((now - pay!) / 60)
            if (t >= 30) {
                ///重新刷新界面
                if let orderId = self.orderModel?.id {
                    self.loadOrderInfo(orderId: orderId)
                }
            }
        }
        return min(t, 30)
    }
}

extension ChatOrderViewModel: RequestCallBack,RequestDataReformer,RequestParamSource {
    
    func reform(_ request: BaseRequest, _ data: [String : Any]?) {
        dPrint(data!)
        if let _ = request as? CancelOredrRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(TradeOrderListModel.self, from: jsonData)
                        self.orderModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_cancel_order,flag, nil)
        }else if let _ = request as? EvaluateOrderRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(TradeOrderListModel.self, from: jsonData)
                        self.orderModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_evaluate_order,flag, nil)
        }else if let _ = request as? ReleseCoinRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(TradeOrderListModel.self, from: jsonData)
                        self.orderModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_relese_coin,flag, nil)
        } else if let _ = request as? AdChatInfoRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(WaitOrderDetailModel.self, from: jsonData)
                        self.waitDetailModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_ad_chat_info,flag, nil)
        }else if let _ = request as? TradeOrderInfoRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(TradeOrderListModel.self, from: jsonData)
                        self.orderModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_order_detail,flag, nil)
        }else if let _ = request as? ConfirmPayRequest {
            var flag = false
            if let data = data?["data"] as? [String:Any] {
                dPrint(data)
                if let jsonData = data.jsonData {
                    do{
                        let model = try JSONDecoder().decode(TradeOrderListModel.self, from: jsonData)
                        self.orderModel = model
                        flag = true
                    }catch {
                        flag = false
                        dPrint(error)
                    }
                }
            }
            self.response?(ResponseState.trade_order_confirmPay,flag, nil)
        }else if let _ = request as? NotifyReleseCoinRequest {
            notifyTime = Date().timeIntervalSince1970
            var t = self.getPayTime()
            t = max(30 - t, 0)
            let text = String(format: kText("已发出系统通知。%d分钟之后,可发起申诉!"), t)
            CYMBShow.showMessage(text)
            self.response?(ResponseState.trade_notify_relese_coin,true, nil)
        }else if let _ = request as? AdChatUpdateRequest {
            self.response?(ResponseState.trade_update_adChatTime,true, nil)
        }else if let _ = request as? OrderChatUpdateRequest {
            self.response?(ResponseState.trade_update_orderChatTime,true, nil)
        }
    }
    
    func requestDidSucess(_ request: BaseRequest) {
    }
    
    func requestDidFail(_ request: BaseRequest) {
        if let _ = request as? CancelOredrRequest {
            self.response?(ResponseState.trade_cancel_order,false, request.errorMsg)
        }else if let _ = request as? EvaluateOrderRequest {
            self.response?(ResponseState.trade_evaluate_order,false, request.errorMsg)
        }else if let _ = request as? ReleseCoinRequest {
            self.response?(ResponseState.trade_relese_coin,false, request.errorMsg)
        }else if let _ = request as? AdChatInfoRequest {
            self.response?(ResponseState.trade_ad_chat_info,false, request.errorMsg)
        }else if let _ = request as? TradeOrderInfoRequest {
            self.response?(ResponseState.trade_order_detail,false, nil)
        }else if let _ = request as? ConfirmPayRequest {
            self.response?(ResponseState.trade_order_confirmPay,false, nil)
        }else if let _ = request as? NotifyReleseCoinRequest {
            self.response?(ResponseState.trade_notify_relese_coin,false, nil)
        }else if let _ = request as? AdChatUpdateRequest {
            self.response?(ResponseState.trade_update_adChatTime,false, nil)
        }else if let _ = request as? OrderChatUpdateRequest {
            self.response?(ResponseState.trade_update_orderChatTime,false, nil)
        }
    }
    
    func requestParams(_ request: BaseRequest) -> [String : Any]? {
        var pramas: [String:Any] = [:]
        if let _ = request as? CancelOredrRequest {
            pramas.updateValue(orderId, forKey: kID)
        }else if let _ = request as? EvaluateOrderRequest {
            pramas.updateValue(orderId, forKey: "id")
            pramas.updateValue(evaluation, forKey: "evaluation")
        }else if let _ = request as? ReleseCoinRequest {
            pramas.updateValue(orderId, forKey: "id")
            pramas.updateValue(payPassword, forKey: "payPassword")
        }else if let _ = request as? AdChatInfoRequest {
            pramas.updateValue(adChatId, forKey: kID)
        }else if let _ = request as? TradeOrderInfoRequest {
            pramas.updateValue(orderId, forKey: kID)
        }else if let _ = request as? ConfirmPayRequest {
            pramas.updateValue(orderId, forKey: kID)
        }else if let _ = request as? NotifyReleseCoinRequest {
            pramas.updateValue(orderId, forKey: kID)
        }else if let _ = request as? AdChatUpdateRequest {
            pramas.updateValue(adChatId, forKey: kID)
        }else if let _ = request as? OrderChatUpdateRequest {
            pramas.updateValue(orderId, forKey: kID)
        }
        return pramas
    }
    
}
